<template>
  <div class="page-order">
    <div class="search-bar">
      <el-form
        :inline="true"
        :model="dataForm"
        @submit.prevent
        @keyup.enter="onGetDataList(page)"
      >
        <div class="input-row">
          <el-form-item :label="$t('order.number') + '：'">
            <el-input
              v-model="dataForm.orderNumber"
              :placeholder="$t('order.number')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('prodList.shopName') + '：'">
            <el-input
              v-model="dataForm.shopName"
              :placeholder="$t('prodList.inputShopName')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.status') + '：'">
            <el-select
              v-model="status"
              clearable
              :placeholder="$t('order.statusMsg')"
              @change="orderStatus"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.afterSalesStatus') + '：'">
            <el-select
              v-model="dataForm.refundStatus"
              clearable
              :placeholder="$t('order.pleSelAfterSalesSta')"
            >
              <el-option
                v-for="item in refund"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.paymentMethod') + '：'">
            <el-select
              v-model="dataForm.payType"
              clearable
              :placeholder="$t('order.paymentMethod')"
            >
              <el-option
                v-for="item in payType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item :label="$t('order.orderType') + '：'">
            <el-select
              v-model="dataForm.orderType"
              clearable
              :placeholder="$t('order.orderType')"
            >
              <el-option
                v-for="item in orderType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item
            :label="$t('order.orderMold') + '：'"
          >
            <el-select
              v-model="dataForm.orderMold"
              clearable
              :placeholder="$t('order.pleaseSelectOrderMold')"
            >
              <el-option
                v-for="item in orderMold"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item :label="$t('order.theRecipientSName') + '：'">
            <el-input
              v-model="dataForm.receiver"
              :placeholder="$t('order.pleaseEnRecipName')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.contactTel') + '：'">
            <el-input
              v-model="dataForm.mobile"
              :placeholder="$t('order.pleaseEnterNumber')"
              clearable
              class="myinput-appearance"
            />
          </el-form-item>
          <el-form-item :label="$t('order.logisticsType') + '：'">
            <el-select
              v-model="dataForm.dvyType"
              clearable
              :placeholder="$t('order.selectLogType')"
            >
              <el-option
                v-for="item in dvyType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item :label="$t('order.pickUpPoint') + '：'">
            <el-input
              v-model="dataForm.stationName"
              :placeholder="$t('order.pickUpPoint')"
              clearable
            />
          </el-form-item> -->
          <el-form-item :label="$t('order.createTime') + '：'">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="—"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
            />
            <div
              style="margin-left: 20px;"
              class="default-btn"
              @click="onSetDateRange(1)"
            >
              {{
                $t("date.t")
              }}
            </div>
            <div
              class="default-btn"
              @click="onSetDateRange(2)"
            >
              {{
                $t("date.y")
              }}
            </div>
            <div
              class="default-btn"
              @click="onSetDateRange(3)"
            >
              {{
                $t("date.n")
              }}
            </div>
            <div
              class="default-btn"
              @click="onSetDateRange(4)"
            >
              {{
                $t("th")
              }}
            </div>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t("order.query") }}
            </div>
            <div
              v-if="isAuth('platform:order:exportExcel')"
              class="default-btn"
              @click="onGetSoldExcel()"
            >
              {{ $t("order.export") }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch()"
            >
              {{ $t("product.reset") }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container main">
      <div class="content">
        <!-- 导航 -->
        <div :class="['order-status-nav','clearfix',showHeadScroll?'status-nav-bottom':'']">
          <ul class="nav-list clearfix">
            <li
              :class="['nav-item', sts == 0 ? 'selected' : '']"
              data-sts="0"
              @click="onSelectNav($event)"
            >
              {{ $t("date.a") }}
            </li>
            <li
              :class="['nav-item', sts == 1 ? 'selected' : '']"
              data-sts="1"
              @click="onSelectNav($event)"
            >
              {{ $t("order.pendingPayment") }}
            </li>
            <li
              :class="['nav-item', sts == 2 ? 'selected' : '']"
              data-sts="2"
              @click="onSelectNav($event)"
            >
              {{ $t("order.toBeShipped") }}
            </li>
            <li
              :class="['nav-item', sts == 3 ? 'selected' : '']"
              data-sts="3"
              @click="onSelectNav($event)"
            >
              {{ $t("order.pendingReceipt") }}
            </li>
            <li
              :class="['nav-item', sts == 4 ? 'selected' : '']"
              data-sts="4"
              @click="onSelectNav($event)"
            >
              部分发货
            </li>
            <li
              :class="['nav-item', sts == 5 ? 'selected' : '']"
              data-sts="5"
              @click="onSelectNav($event)"
            >
              {{ $t("order.successfulTransaction") }}
            </li>
            <li
              :class="['nav-item', sts == 6 ? 'selected' : '']"
              data-sts="6"
              @click="onSelectNav($event)"
            >
              {{ $t("order.transactionFailed") }}
            </li>
            <!-- <li
              :class="['nav-item', sts == 7 ? 'selected' : '']"
              data-sts="7"
              @click="onSelectNav($event)"
            >
              {{ $t("group.waitGroup") }}
            </li> -->
          </ul>
          <ul class="nav-right" />
        </div>

        <!-- 列标题 -->
        <div :class="['tit', showHeadScroll ? sidebarFold?'fixed-top-fold':'fixed-top' : '']">
          <el-row style="width: 100%">
            <el-col :span="7">
              <span class="item product">{{ $t("group.prodInfo") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="transaction-price"
            >
              <span class="item">{{ $t("prodList.goodsPrice") }}/{{
                $t("order.quantity")
              }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("order.paymentAmount") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.paymentMethod") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("order.buyerConsignee") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.orderStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.afterSalesStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.operation") }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="order in dataList"
          :key="order.orderId"
          class="prod"
        >
          <div class="prod-tit">
            <span>{{ $t("order.number") }}：{{ order.orderNumber }}</span>
            <span>{{ $t("order.createTime") }}：{{ order.createTime }}</span>
            <span>{{ $t("prodList.shopName") }}：{{ order.shopName }}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width: 100%">
              <el-col
                :span="10"
                style="height: 100%"
              >
                <div class="item prod-item">
                  <div
                    v-for="orderItem in order.orderItems"
                    :key="orderItem.orderItemId"
                    class="items name"
                  >
                    <!-- 商品信息 -->
                    <div class="order-prod-item-info">
                      <div class="info">
                        <div class="prod-image">
                          <prod-pic
                            width="60px"
                            height="60px"
                            :pic="orderItem.pic"
                          />
                        </div>
                        <div class="prod-name">
                          <div class="prod-con">
                            <div class="prod-name-txt">
                              {{ orderItem.prodName }}
                            </div>
                            <div
                              v-if="orderItem.skuName"
                              class="prod-name-sku"
                            >
                              {{ orderItem.skuName }}
                            </div>
                            <div
                              v-if="order.orderType === 1 || order.orderType === 2"
                              class="order-status"
                            >
                              {{
                                order.orderType === 1
                                  ? $t("order.groupPurchaseOrder")
                                  : order.orderType === 2
                                    ? $t("order.spikeOrder")
                                    : ""
                              }}
                            </div>
                            <div
                              v-if="order.orderMold === 1"
                              class="order-status"
                            >
                              {{ $t("order.virtualOrder") }}
                            </div>
                            <div
                              v-if="
                                !orderItem.returnMoneySts ||
                                  orderItem.returnMoneySts < 0 ||
                                  orderItem.returnMoneySts > 5
                              "
                              class="order-status"
                            >
                              <template v-if="[2, 4].includes(order.status)">
                                {{
                                  orderItem.status === 0 ? '发货完成' : orderItem.status == -1 ? '待发货' : '部分发货'
                                }}
                              </template>
                              <template v-else>
                                {{
                                  [
                                    "",
                                    $t("order.pendingPayment"),
                                    $t("order.toBeShipped"),
                                    $t("order.pendingReceipt"),
                                    "部分发货",
                                    $t("order.successfulTransaction"),
                                    $t("order.transactionFailed"),
                                    $t("group.waitGroup"),
                                  ][order.status]
                                }}
                              </template>
                            </div>
                            <div
                              v-else
                              class="order-status"
                            >
                              {{
                                [
                                  "",
                                  $t("refundOrderDetail.buyerApply"),
                                  $t("order.sellerAccepts"),
                                  $t("refundOrderDetail.buyerDelivery"),
                                  $t("refundOrderDetail.sellerReceivesGoods"),
                                  $t("order.refundsuccessfully"),
                                ][orderItem.returnMoneySts]
                              }}
                            </div>
                            <div
                              v-if="order.dvyType === 2 || order.dvyType === 4"
                              class="order-status"
                            >
                              {{
                                order.dvyType === 2
                                  ? $t("order.selfMention")
                                  : order.dvyType === 4
                                    ? $t("order.sameCityDelivery")
                                    : ""
                              }}
                            </div>
                            <div
                              v-if="orderItem.preSellTime && orderItem.preSellTime !== null"
                              class="order-status"
                            >
                              {{ $t('order.EstimatedDeliveryTime') }}{{ preSellTimeShowHandler(orderItem.preSellTime) }}
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- 赠品信息 -->
                      <div
                        v-if="orderItem.giveawayList"
                        class="order-prod-item-give-con"
                      >
                        <div
                          v-for="(giveawayItem, giveIndex) in orderItem.giveawayList"
                          :key="giveIndex"
                          class="giveaway-item"
                        >
                          <div class="giveaway-name">
                            【{{ $t('order.giveawayPord') }}】 {{ giveawayItem.prodName }}
                          </div>
                          <div class="giveaway-name giveaway-sku-name">
                            {{ giveawayItem.skuName || '' }}
                          </div>
                          <div class="giveaway-item-sku-count">
                            x{{ giveawayItem.prodCount }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="prod-price">
                      <span>{{ moneyFormat(orderItem.price) }}</span>
                      <span>{{ orderItem.prodCount }}{{ $t("marketing.item") }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%;text-align: center;"
              >
                <div class="item">
                  <div>
                    <span class="totalprice">
                      {{ moneyFormat(order.actualTotal) }}
                      {{
                        order.score && order.score > 0
                          ? "+ " + order.score + $t("order.score")
                          : ""
                      }}
                    </span>
                    <span
                      v-if="order.freightAmount - order.platformFreeFreightAmount > 0"
                      class="totalprice"
                    >
                      （{{ $t("order.includingFreight") }}：
                      {{ moneyFormat(order.freightAmount - order.platformFreeFreightAmount) }}）
                    </span>
                    <span>
                      {{ $t("order.total") }}
                      {{ order.productNums }}
                      {{ $t("order.piece") }}
                    </span>
                    <div
                      v-if="order.status === 1 && order.isSelf == 1"
                      class="default-btn text-btn"
                      @click="editAmount(order)"
                    >
                      修改金额
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span v-if="(!order.payType && order.payType != 0) || order.status === 1">{{
                      $t("order.unpaid")
                    }}</span>
                    <span v-else>
                      {{
                        [
                          $t("order.pointsPayment"),
                          $t("order.wecProPay"),
                          $t("order.alipayPCPayment"),
                          $t("order.wechatScanCodePayment"),
                          $t("order.wechatH5Payment"),
                          $t("order.weclAccountPay"),
                          $t("order.alipayH5Payment"),
                          $t("order.alipayAPPPayment"),
                          $t("order.wechatAPPPayment"),
                          $t("order.balancePayment"),
                          $t("order.payPalPayment"),
                          "",
                          "线下付款"
                        ][order.payType]
                      }}
                    </span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <div class="buyer-name">
                      {{ order.receiverName }}
                    </div>
                    <div class="buyer-phone">
                      {{ order.receiverMobile }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span>
                    <span
                      v-if="order.status === 1"
                      type="danger"
                    >{{ $t("order.pendingPayment") }}</span>
                    <span
                      v-else-if="order.status === 2"
                      type="danger"
                    >{{ $t("order.toBeShipped") }}</span>
                    <span
                      v-else-if="order.status === 3"
                      type="danger"
                    >{{ $t("order.pendingReceipt") }}</span>
                    <span
                      v-else-if="order.status === 4"
                      type="danger"
                    >部分发货</span>
                    <span
                      v-else-if="order.status === 5"
                      type="danger"
                    >{{ $t("order.successfulTransaction") }}</span>
                    <span
                      v-else-if="order.status === 6"
                    >{{
                      $t("order.transactionFailed")
                    }}</span>
                    <span
                      v-else-if="order.status === 7"
                      type="danger"
                    >{{ $t("group.waitGroup") }}</span>
                  </span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span
                    v-if="order.refundStatus === 1"

                    type="danger"
                  >{{ $t("order.requestARefund") }}</span>
                  <span
                    v-else-if="order.refundStatus === 2"

                    type="danger"
                  >{{ $t("order.refundsuccessfully") }}</span>
                  <span
                    v-else-if="order.refundStatus === 3"

                    type="danger"
                  >{{ $t("order.partialRefundSucc") }}</span>
                  <span
                    v-else-if="order.refundStatus === 4"

                    type="danger"
                  >{{ $t("order.refundFailed") }}</span>
                  <span
                    v-else

                    type="danger"
                  >{{
                    $t("order.noAfterSales")
                  }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="operate">
                    <div
                      class="default-btn text-btn"
                      @click="onAddOrUpdate(order.orderNumber)"
                    >
                      {{ $t("order.seeDetails") }}
                    </div>
                    <div
                      class="default-btn text-btn"
                      @click="toImbox(order)"
                    >
                      {{ $t("order.contactBuyer") }}
                    </div>
                    <div
                      v-if="order.refundStatus"
                      class="default-btn text-btn"
                      @click="onRefundRoute(order.orderNumber)"
                    >
                      {{ $t("order.refundInformation") }}
                    </div>
                    <div
                      v-if="order.status == 1 && order.isSelf == 1"
                      class="default-btn text-btn"
                      @click="onSetStatus(order)"
                    >
                      修改订单
                    </div>
                    <div
                      v-if="(order.status == 2 || order.status == 4) && order.isSelf == 1"
                      class="default-btn text-btn"
                      @click="changeOrder(order)"
                    >
                      发货
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div
          v-if="!dataList.length"
          class="empty"
        >
          {{ $t("order.noData") }}
        </div>
      </div>
    </div>
    <el-pagination
      v-if="dataList.length"
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />

    <set-status
      ref="setStatusRef"
      @ok="onGetDataList"
    />

    <order-delivery-update
      v-if="devyVisible"
      ref="orderDeliveryUpdateRef"
      @refresh-order-delivery-update="onGetDataList"
    />

    <orderAmount-update
      v-if="orderAmountUpdateVisible"
      ref="orderAmountUpdateRef"
      @refresh-order-amount-update="onGetDataList"
    />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import moment from 'moment'
import Big from 'big.js'
import setStatus from '../components/status.vue'
import OrderDeliveryUpdate from '../components/order-delivery-update.vue'
import OrderAmountUpdate from '../components/orderAmount-update.vue'

// eslint-disable-next-line no-undef
defineOptions({
  name: 'order/order/index'
})

const options = [
  {
    value: 1,
    label: $t('order.pendingPayment')
  },
  {
    value: 2,
    label: $t('order.toBeShipped')
  },
  {
    value: 3,
    label: $t('order.pendingReceipt')
  },
  {
    value: 4,
    label: '部分发货'
  },
  {
    value: 5,
    label: $t('order.successfulTransaction')
  },
  {
    value: 6,
    label: $t('order.transactionFailed')
  }
  // {
  //   value: 7,
  //   label: $t('group.waitGroup')
  // }
]
const refund = [{
  value: 0,
  label: $t('order.noAfterSales')
}, {
  value: 1,
  label: $t('order.requestARefund')
}, {
  value: 2,
  label: $t('order.refundsuccessfully')
}, {
  value: 3,
  label: $t('order.partialRefundSucc')
}, {
  value: 4,
  label: $t('order.refundFailed')
}]
const orderType = [{
  value: 0,
  label: $t('order.normalOrder')
}, {
  value: 1,
  label: $t('order.groupPurchaseOrder')
}, {
  value: 2,
  label: $t('order.spikeOrder')
}]
const orderMold = [{
  value: 0,
  label: $t('order.physicalOrder')
}, {
  value: 1,
  label: $t('order.virtualOrder')
}]
const dvyType = [{
  value: 1,
  label: $t('order.expressDelivery')
},
{
  value: 2,
  label: $t('order.selfMention')
},
{
  value: 3,
  label: $t('order.noNeedRequired')
},
{
  value: 4,
  label: $t('order.sameCityDelivery')
}]

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

const payType = computed(() => {
  const typeVal = [{
    value: -1,
    label: $t('order.unpay')
  }, {
    value: 0,
    label: $t('order.pointsPayment')
  }, {
    value: 1,
    label: $t('order.weixinPay')
  }, {
    value: 2,
    label: $t('order.aliPay')
  }, {
    value: 3,
    label: $t('publics.balancePay')
  }, {
    value: 4,
    label: $t('order.payPalPayment')
  }]
  if (paySettlementType.value === 1) {
    return typeVal.filter((item) => {
      return item.value !== 4
    })
  }
  return typeVal
})

// 二级菜单折叠状态
const commonStore = useCommonStore()
const sidebarFold = computed({
  get () { return commonStore.sidebarFold },
  set (val) { commonStore.updateSidebarFold(val) }
})

const route = useRoute()
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
onActivated(() => {
  const query = route.query
  if (Object.keys(query).length > 0) {
    onGetDataList(page, query)
  }
})

let resizeProportion = 1
const sts = ref(0)
const status = ref(null)
onMounted(() => {
  sts.value = route.query.status || 0
  status.value = sts.value === 0 ? null : sts.value

  // 携带参数查询
  onGetDataList(page, route.query)

  // 监听页面滚动
  window.addEventListener('scroll', onScrollToTop)

  resizeProportion = window.outerHeight / window.innerHeight
  window.addEventListener('resize', function () {
    resizeProportion = window.outerHeight / window.innerHeight
  })
})

/**
 * 页面滚动事件
 */
const showHeadScroll = ref(false)
const onScrollToTop = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > (400 * resizeProportion)
}

/**
 * 获取数据列表
 */
let tempSearchForm = null // 保存上次点击查询的请求条件
let oldPar = {}
const dataForm = ref({})
const dateRange = ref([])
const dataList = ref([])
const onGetDataList = (pageParam, params, type = 0, newData = false) => {
  let par = Object.assign(
    {
      orderNumber: dataForm.value.orderNumber,
      shopName: dataForm.value.shopName,
      orderType: dataForm.value.orderType,
      orderMold: dataForm.value.orderMold,
      payType: dataForm.value.payType,
      receiver: dataForm.value.receiver,
      mobile: dataForm.value.mobile,
      status: status.value,
      dvyType: dataForm.value.dvyType,
      stationName: dataForm.value.stationName,
      refundStatus: dataForm.value.refundStatus,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    },
    params
  )
  if (type === 0) {
    oldPar = par
  } else {
    par = oldPar
  }
  if (newData || !tempSearchForm) {
    tempSearchForm = par
  } else {
    tempSearchForm.status = status.value
  }
  const pageVal = (pageParam === undefined ? page : pageParam)
  http({
    url: http.adornUrl('/platform/order/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageVal === null ? page.currentPage : pageVal.currentPage,
          size: pageVal === null ? page.pageSize : pageVal.pageSize
        },
        tempSearchForm
      ), false
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    sts.value = !status.value ? 0 : status.value
  })
}
// 每页数
const sizeChangeHandle = (val) => {
  page.pageSize = val
  page.currentPage = 1
  onGetDataList(page, {}, 1)
}
// 当前页
const currentChangeHandle = (val) => {
  page.currentPage = val
  onGetDataList(page, {}, 1)
}

/**
 * 导航选择状态
 */
const onSelectNav = (e) => {
  const stsVal = e.currentTarget.dataset.sts
  sts.value = parseInt(stsVal)
  status.value = sts.value === 0 ? null : parseInt(stsVal)
  page.currentPage = 1
  onGetDataList(page)
}
const orderStatus = (val) => {
  status.value = val
  sts.value = val
  onGetDataList()
}
/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const onSetDateRange = (val) => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -7
    endDay = -1
  } else if (val === 4) {
    startDay = -30
    endDay = -1
  } else {
    return
  }
  // 开始时间
  const startTime = moment().add(startDay, 'days').startOf('days').format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  dateRange.value = [startTime, endTime]
}
// 新增 / 修改
const router = useRouter()
const onAddOrUpdate = (val) => {
  router.push({
    path: '/order/order-info/index',
    query: {
      orderNumber: val
    }
  })
}
// 前往消息盒子
const toImbox = (order) => {
  if (order.userWriteOff) {
    ElMessage({
      message: $t('order.userlogoutTips'),
      type: 'error'
    })
    return
  }
  if (isAuth('message:message:view')) {
    const path = router.resolve({
      path: '/message-box/index',
      query: {
        userId: order.userId,
        orderNumber: order.orderNumber
      }
    })
    window.open(path.href, 'view_window', 'noopener,noreferrer')
  } else {
    ElMessage.info($t('home.authTip'))
  }
}
// 退款路由跳转
const routerStore = useRouterStore()
const onRefundRoute = (val) => {
  routerStore.updateIncludePageList('order/order-refund/index')
  routerStore.pushHisPageList('order/order-refund/index')
  router.push({
    path: '/order/order-refund/index',
    query: { orderNumber: val }
  })
}
// 清空按钮
const onResetSearch = () => {
  dataForm.value = {}
  dateRange.value = []
  status.value = null
}
// 搜索查询
const onSearch = (newData = false) => {
  page.currentPage = 1
  onGetDataList(page, null, 0, newData)
}

const lang = localStorage.getItem('bbcLang') || 'zh_CN'
const onGetSoldExcel = () => {
  if (!dateRange.value || dateRange.value.length < 2) {
    ElMessage.error($t('order.pleExpOrderFirst'))
    return
  }
  ElMessageBox.confirm($t('order.exportReport'), $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      target: '.page-order',
      customClass: 'export-load',
      background: 'transparent',
      text: $t('shop.exportIng')
    })
    http({
      url: http.adornUrl('/platform/order/soldExcel'),
      method: 'get',
      params: http.adornParams({
        orderNumber: dataForm.value.orderNumber,
        shopName: dataForm.value.shopName,
        orderType: dataForm.value.orderType,
        payType: dataForm.value.payType,
        receiver: dataForm.value.receiver,
        mobile: dataForm.value.mobile,
        orderMold: dataForm.value.orderMold,
        lang: lang === 'en' ? 1 : 0,
        status: status.value,
        dvyType: dataForm.value.dvyType,
        stationName: dataForm.value.stationName,
        refundStatus: dataForm.value.refundStatus,
        startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
        endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
      }),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      loading.close()
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = $t('order.orderInfCollationXls')
      const elink = document.createElement('a')
      if ('download' in elink) { // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }).catch((e) => {
      loading.close()
    })
  })
}

/**
 * 预售时间显示为 ’YYYY-MM-DD‘
 */
const preSellTimeShowHandler = (val) => {
  if (!val) return val
  return val.slice(0, -8).trim()
}

const setStatusRef = ref(null)
const onSetStatus = (order) => {
  setStatusRef.value?.init([order])
}

/**
 * 更改订单金额
 */
const orderAmountUpdateVisible = ref(false)
const orderAmountUpdateRef = ref(null)
const editAmount = (order) => {
  orderAmountUpdateVisible.value = true
  nextTick(() => {
    orderAmountUpdateRef.value?.init(order)
  })
}

/**
 * 发货
*/
const orderDeliveryUpdateRef = ref(null)
const devyVisible = ref(false)
const changeOrder = (order) => {
  devyVisible.value = true
  nextTick(() => {
    orderDeliveryUpdateRef.value?.init(order)
  })
}
</script>
<style lang="scss" scoped>
@use './index.scss';
</style>
